import React, { useState, useEffect } from 'react';
import { Button, Input, Tag, Space, Popconfirm, message, Select, Switch, Form, Modal, Upload } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { 
  PlusOutlined, 
  SearchOutlined, 
  DeleteOutlined, 
  EditOutlined, 
  CodeOutlined, 
  TagOutlined,
  OrderedListOutlined,
  FireOutlined,
  CheckOutlined,
  CloseOutlined,
  UploadOutlined,
  InboxOutlined
} from '@ant-design/icons';
import { FilterCard, TableCard } from '@/components/common';
import { Problem } from '@/types/problem';
import { problemService } from '@/services/problemService';
import { getDifficultyTag } from '@/utils/difficulty';
import { getTagColor } from '@/utils/tags';

const { Option } = Select;
const { Dragger } = Upload;

interface ProblemListProps {
  isAdmin?: boolean;
  basePath?: string;
}

const ProblemList: React.FC<ProblemListProps> = ({ 
  isAdmin = false,
  basePath = '/problem' 
}) => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 从URL参数初始化状态
  const initialPage = parseInt(searchParams.get('page') || '1');
  const initialKeyword = searchParams.get('keyword') || '';
  const initialContestFilter = searchParams.get('contestFilter') || 'none';
  
  const [loading, setLoading] = useState(false);
  const [problems, setProblems] = useState<Problem[]>([]);
  const [filteredProblems, setFilteredProblems] = useState<Problem[]>([]);
  const [pagination, setPagination] = useState({
    current: initialPage,
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState(initialKeyword);
  const [contestFilter, setContestFilter] = useState(initialContestFilter);
  
  // 导入功能相关状态
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [importType, setImportType] = useState<'qduoj' | 'fps'>('qduoj');
  const [importLoading, setImportLoading] = useState(false);
  const [importFile, setImportFile] = useState<File | null>(null);

  const fetchProblems = async (page = 1, keyword = '', updateUrl = true) => {
    try {
      setLoading(true);
      
      // 只在需要时更新URL参数
      if (updateUrl) {
        const newSearchParams = new URLSearchParams();
        if (page > 1) newSearchParams.set('page', page.toString());
        if (keyword) newSearchParams.set('keyword', keyword);
        if (contestFilter !== 'none') newSearchParams.set('contestFilter', contestFilter);
        setSearchParams(newSearchParams);
      }
      
      const response = await problemService.getProblems({
        page,
        limit: pagination.pageSize,
        keyword,
      });
      
      if (response.data) {
        const problemData = 'data' in response.data ? response.data.data : response.data;
        const allProblems = problemData.results || [];
        
        setProblems(allProblems);
        
        // 应用contest过滤
        let filtered = allProblems;
        if (contestFilter === 'none') {
          filtered = allProblems.filter(p => !p.contest_id);
        } else if (contestFilter === 'contest') {
          filtered = allProblems.filter(p => p.contest_id);
        }
        
        setFilteredProblems(filtered);
        setPagination({
          ...pagination,
          current: page,
          total: problemData.count || 0,
        });
      }
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProblems(initialPage, initialKeyword);
  }, []);

  // 监听URL参数变化，当用户通过浏览器前进/后退按钮时重新加载数据
  useEffect(() => {
    const page = parseInt(searchParams.get('page') || '1');
    const keyword = searchParams.get('keyword') || '';
    const contestFilterParam = searchParams.get('contestFilter') || 'none';
    
    // 只有当参数真正变化时才重新加载
    if (page !== pagination.current || keyword !== searchKeyword || contestFilterParam !== contestFilter) {
      setSearchKeyword(keyword);
      setContestFilter(contestFilterParam);
      fetchProblems(page, keyword, false); // 不更新URL，避免循环
    }
  }, [searchParams]);

  // 当contestFilter变化时，重新过滤题目
  useEffect(() => {
    if (problems.length > 0) {
      let filtered = problems;
      if (contestFilter === 'none') {
        filtered = problems.filter(p => !p.contest_id);
      } else if (contestFilter === 'contest') {
        filtered = problems.filter(p => p.contest_id);
      }
      setFilteredProblems(filtered);
    }
  }, [contestFilter, problems]);

  const handleSearch = () => {
    fetchProblems(1, searchKeyword);
  };

  const handleContestFilterChange = (value: string) => {
    setContestFilter(value);
  };

  const handleDelete = async (id: number) => {
    try {
      await problemService.deleteProblem(id);
      message.success('删除成功');
      fetchProblems(pagination.current);
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理visible属性切换
  const handleVisibleChange = async (id: number, visible: boolean) => {
    try {
      await problemService.patchProblem(id, { visible });
      message.success(`题目已${visible ? '公开' : '隐藏'}`);
      // 更新本地状态
      setProblems(problems.map(p => 
        p.id === id ? { ...p, visible } : p
      ));
      setFilteredProblems(filteredProblems.map(p => 
        p.id === id ? { ...p, visible } : p
      ));
    } catch (error) {
      message.error('更新失败');
    }
  };

  // 导入功能相关方法
  const showImportModal = (type: 'qduoj' | 'fps') => {
    setImportType(type);
    setImportModalVisible(true);
    setImportFile(null);
  };

  const handleImport = async () => {
    console.log('Import file:', importFile); // 调试日志
    if (!importFile) {
      message.error('请选择要导入的文件');
      return;
    }

    try {
      setImportLoading(true);
      const formData = new FormData();
      formData.append('file', importFile);

      const response = importType === 'qduoj' 
        ? await problemService.importQduojProblems(formData)
        : await problemService.importFpsProblems(formData);

      if (response.data.code === 200) {
        message.success(response.data.message);
        setImportModalVisible(false);
        setImportFile(null);
        // 刷新题目列表
        fetchProblems(pagination.current, searchKeyword);
      } else {
        message.error(response.data.message);
      }
          } catch (error: any) {
        console.error('Import error:', error);
        
        // 处理超时错误
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          message.error('上传超时，请检查网络连接或尝试上传较小的文件');
        } else if (error.response?.data?.message) {
          message.error(error.response.data.message);
        } else if (error.message) {
          message.error(`导入失败: ${error.message}`);
        } else {
          message.error(`导入失败: ${error.toString()}`);
        }
      } finally {
      setImportLoading(false);
    }
  };

  const handleFileChange = (info: any) => {
    const { file, fileList } = info;
    console.log('File change:', file, fileList); // 调试日志
    
    // 如果文件被移除，清空选择
    if (file.status === 'removed') {
      setImportFile(null);
      return;
    }
    
    // 只处理第一个文件，确保单文件选择
    const targetFile = fileList && fileList.length > 0 ? fileList[0] : file;
    
    if (targetFile && targetFile.originFileObj) {
      setImportFile(targetFile.originFileObj);
    } else if (targetFile && targetFile instanceof File) {
      setImportFile(targetFile);
    }
  };

  const getColumns = () => {
    const baseColumns = [
      {
        title: '状态',
        key: 'status',
        width: 60,
        render: (_: any, record: Problem) => {
          if (record.user_status === true) {
            return <CheckOutlined style={{ color: '#52c41a' }} />;
          } else if (record.user_status === false) {
            return <CloseOutlined style={{ color: '#ff4d4f' }} />;
          } else {
            return <span>-</span>;
          }
        },
      },
      {
        title: <><OrderedListOutlined /> ID</>,
        dataIndex: '_id',
        width: 80,
      },
      {
        title: <><FireOutlined /> 标题</>,
        dataIndex: 'title',
        render: (text: string, record: Problem) => (
                  <a 
          onClick={() => navigate(`/problem/${record.id}/submit?origin=system`)}
          style={{ color: 'var(--primary-color)', cursor: 'pointer' }}
        >
          {text}
        </a>
        ),
      },
      {
        title: '难度',
        dataIndex: 'difficulty',
        width: 90,
        render: (text: string) => getDifficultyTag(text),
      },
      {
        title: <><TagOutlined /> 标签</>,
        dataIndex: 'tags',
        render: (tags: { id: number; name: string }[]) => (
          <Space size={[0, 4]} wrap>
            {tags?.map(tag => (
              <Tag key={tag.id} color={getTagColor(tag.name)}>{tag.name}</Tag>
            ))}
          </Space>
        ),
      },
      {
        title: '提交情况',
        key: 'submissions',
        render: (_: any, record: Problem) => {
          const acceptanceRatio = (record.submission_number ?? 0) > 0 
            ? Math.round(((record.accepted_number ?? 0) / (record.submission_number ?? 1)) * 100) 
            : 0;
          
          return (
            <span>
              {record.submission_number ?? 0} 次提交 / {acceptanceRatio}% 通过率
            </span>
          );
        },
      },
      {
        title: '来源',
        key: 'source',
        width: 100,
        render: (_: any, record: Problem) => (
          record.contest_id ? 
            <Tag color="blue">比赛题目</Tag> : 
            <Tag>普通题目</Tag>
        ),
      },
    ];

    // 对于所有用户都能看到的"答题"按钮
    const actionColumn = {
      title: '操作',
      key: 'action',
      width: isAdmin ? 220 : 80,
      render: (_: any, record: Problem) => (
        <Space size="small">
          {isAdmin && (
            <Switch
              size="small"
              checked={record.visible}
              checkedChildren="公开"
              unCheckedChildren="私有"
              onChange={(checked) => handleVisibleChange(record.id, checked)}
            />
          )}
          <Button 
            type="link" 
            size="small"
            icon={<CodeOutlined />} 
            onClick={() => navigate(`/problem/${record.id}/submit?origin=system`)}
          >
            答题
          </Button>
          
          {isAdmin && (
            <>
              <Button 
                type="link" 
                size="small"
                icon={<EditOutlined />} 
                onClick={() => {
                  const currentUrl = window.location.pathname + window.location.search;
                  navigate(`${basePath}/edit/${record.id}?returnUrl=${encodeURIComponent(currentUrl)}`);
                }}
              >
                编辑
              </Button>
              <Popconfirm
                title="确定要删除这道题目吗？"
                onConfirm={() => handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  type="link" 
                  size="small"
                  danger 
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </Space>
      ),
    };

    return [...baseColumns, actionColumn];
  };

  const [form] = Form.useForm();

  const handleFormFinish = (values: any) => {
    setSearchKeyword(values.keyword || '');
    setContestFilter(values.contestFilter || 'all');
    // 搜索时重置到第1页
    fetchProblems(1, values.keyword || '');
  };

  const handleReset = () => {
    setSearchKeyword('');
    setContestFilter('all');
    // 重置时回到第1页
    fetchProblems(1, '');
  };

  return (
    <div>
      <FilterCard
        pageTitle="题目列表"
        titleIcon={<OrderedListOutlined />}
        form={form}
        onFinish={handleFormFinish}
        onReset={handleReset}
        extra={
          isAdmin ? (
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => navigate(`${basePath}/create`)}
              >
                新建题目
              </Button>
              <Button
                icon={<UploadOutlined />}
                onClick={() => showImportModal('qduoj')}
              >
                导入QDUOJ题目
              </Button>
              <Button
                icon={<UploadOutlined />}
                onClick={() => showImportModal('fps')}
              >
                导入FPS题目
              </Button>
            </Space>
          ) : null
        }
      >
        <Form.Item name="keyword" label="关键词">
          <Input placeholder="搜索题目" style={{ width: 200 }} />
        </Form.Item>
        {isAdmin && (
          <Form.Item name="contestFilter" label="题目类型">
            <Select style={{ width: 120 }}>
              <Option value="all">全部题目</Option>
              <Option value="none">普通题目</Option>
              <Option value="contest">比赛题目</Option>
            </Select>
          </Form.Item>
        )}
      </FilterCard>

      <TableCard
        tableProps={{
          columns: getColumns(),
          dataSource: filteredProblems,
          rowKey: 'id',
          pagination: {
            ...pagination,
            onChange: (page) => fetchProblems(page, searchKeyword),
            showSizeChanger: false,
          },
          loading: loading,
          size: 'small',
        }}
      />

      {/* 导入题目弹出窗口 */}
      <Modal
        title={`导入${importType === 'qduoj' ? 'QDUOJ' : 'FPS'}题目`}
        open={importModalVisible}
        onOk={handleImport}
        onCancel={() => setImportModalVisible(false)}
        confirmLoading={importLoading}
        okText="导入"
        cancelText="取消"
        width={500}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <Dragger
            name="file"
            multiple={false}
            accept={importType === 'qduoj' ? '.zip' : '.xml'}
            onChange={handleFileChange}
            beforeUpload={() => false}
            showUploadList={true}
            maxCount={1}
            fileList={importFile ? [{ uid: '-1', name: importFile.name, status: 'done' }] : []}
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
              支持上传{importType === 'qduoj' ? 'ZIP' : 'XML'}格式文件，每次只能选择一个文件
            </p>
          </Dragger>
          <div style={{ marginTop: 16, fontSize: 12, color: '#666' }}>
            <p>• 支持{importType === 'qduoj' ? 'ZIP' : 'XML'}格式的题目包文件</p>
            <p>• 请确保文件包含完整的题目信息</p>
            <p>• 导入过程可能需要一些时间，请耐心等待</p>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default ProblemList; 